<template>
  <lay-layer
    v-model="visible"
    title="订单发货"
    :area="['600px', 'auto']"
    :shade="true"
    :shade-close="false"
    :move="true"
  >
    <div class="shipment-dialog">
      <div v-if="order" class="order-info">
        <h4>订单信息</h4>
        <div class="order-summary">
          <div class="summary-item">
            <span class="label">订单号：</span>
            <span class="value">{{ order.orderNo }}</span>
          </div>
          <div class="summary-item">
            <span class="label">收货人：</span>
            <span class="value">{{ order.consigneeName }}</span>
          </div>
          <div class="summary-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ order.consigneePhone }}</span>
          </div>
          <div class="summary-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ getFullAddress(order) }}</span>
          </div>
        </div>
      </div>

      <lay-form 
        :model="shipmentForm" 
        ref="shipmentFormRef"
        :rules="formRules"
        label-width="100px"
      >
        <lay-form-item label="物流公司" prop="shippingCompany" required>
          <lay-select 
            v-model="shipmentForm.shippingCompany" 
            placeholder="请选择物流公司"
            allow-clear
          >
            <lay-select-option 
              v-for="company in shippingCompanies" 
              :key="company.value" 
              :value="company.value"
            >
              {{ company.label }}
            </lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="快递单号" prop="trackingNumber" required>
          <lay-input 
            v-model="shipmentForm.trackingNumber" 
            placeholder="请输入快递单号"
            allow-clear
          />
        </lay-form-item>

        <lay-form-item label="物流备注" prop="shippingNotes">
          <lay-textarea 
            v-model="shipmentForm.shippingNotes" 
            placeholder="请输入物流备注信息（选填）"
            :rows="3"
            :maxlength="200"
            show-count
          />
        </lay-form-item>


      </lay-form>

      <!-- 快递单号验证 -->
      <div class="tracking-validation" v-if="shipmentForm.trackingNumber && shipmentForm.shippingCompany">
        <lay-button 
          type="primary" 
          size="sm" 
          @click="validateTracking"
          :loading="validating"
        >
          验证快递单号
        </lay-button>
        <div v-if="trackingValidation.checked" class="validation-result">
          <lay-tag :type="trackingValidation.valid ? 'normal' : 'danger'">
            {{ trackingValidation.valid ? '单号有效' : '单号无效' }}
          </lay-tag>
          <span class="validation-message">{{ trackingValidation.message }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="dialog-footer">
        <lay-button @click="handleCancel">取消</lay-button>
        <lay-button 
          type="primary" 
          @click="handleConfirm"
          :loading="submitting"
        >
          确认发货
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { layer } from '@layui/layer-vue'
import { orderApi, type Order } from '@/api/module/order'

interface Props {
  visible: boolean
  order: Order | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const submitting = ref(false)
const validating = ref(false)
const shipmentFormRef = ref()

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 发货表单
const shipmentForm = reactive({
  shippingCompany: '',
  trackingNumber: '',
  shippingNotes: ''
})

// 快递单号验证结果
const trackingValidation = reactive({
  checked: false,
  valid: false,
  message: ''
})

// 物流公司列表
const shippingCompanies = [
  { label: '顺丰速运', value: 'SF' },
  { label: '圆通速递', value: 'YTO' },
  { label: '中通快递', value: 'ZTO' },
  { label: '申通快递', value: 'STO' },
  { label: '韵达速递', value: 'YD' },
  { label: '百世快递', value: 'HTKY' },
  { label: '德邦快递', value: 'DBL' },
  { label: '京东物流', value: 'JD' },
  { label: '邮政EMS', value: 'EMS' },
  { label: '天天快递', value: 'HHTT' },
  { label: '宅急送', value: 'ZJS' },
  { label: '国通快递', value: 'GTO' }
]

// 表单验证规则
const formRules = {
  shippingCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNumber: [
    { required: true, message: '请输入快递单号', trigger: 'blur' },
    { 
      pattern: /^[A-Za-z0-9]{8,30}$/, 
      message: '快递单号格式不正确', 
      trigger: 'blur' 
    }
  ]
}

// 监听对话框显示状态
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    resetForm()
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(shipmentForm, {
    shippingCompany: '',
    trackingNumber: '',
    shippingNotes: ''
  })
  
  Object.assign(trackingValidation, {
    checked: false,
    valid: false,
    message: ''
  })
  
  shipmentFormRef.value?.clearValidate()
}

// 获取完整地址
const getFullAddress = (order: Order) => {
  return order.consigneeAddress || '-'
}

// 验证快递单号
const validateTracking = async () => {
  if (!shipmentForm.trackingNumber || !shipmentForm.shippingCompany) {
    layer.msg('请先填写物流公司和快递单号', { icon: 0 })
    return
  }

  try {
    validating.value = true
    
    // 模拟快递单号验证API调用
    // 实际项目中应该调用真实的快递查询API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 简单的单号格式验证
    const isValidFormat = /^[A-Za-z0-9]{8,30}$/.test(shipmentForm.trackingNumber)
    
    trackingValidation.checked = true
    trackingValidation.valid = isValidFormat
    trackingValidation.message = isValidFormat 
      ? '快递单号格式正确' 
      : '快递单号格式不正确，请检查后重新输入'
    
    if (isValidFormat) {
      layer.msg('快递单号验证通过', { icon: 1 })
    } else {
      layer.msg('快递单号验证失败', { icon: 2 })
    }
  } catch (error) {
    console.error('验证快递单号失败:', error)
    layer.msg('验证快递单号失败', { icon: 2 })
  } finally {
    validating.value = false
  }
}

// 确认发货
const handleConfirm = async () => {
  if (!props.order) return

  try {
    // 表单验证
    const valid = await shipmentFormRef.value?.validate()
    if (!valid) return

    // 如果已验证快递单号但验证失败，提示用户
    if (trackingValidation.checked && !trackingValidation.valid) {
      const confirm = await layer.confirm('快递单号验证失败，确定要继续发货吗？', {
        title: '确认发货',
        icon: 3
      })
      if (!confirm) return
    }

    submitting.value = true

    const shipmentData = {
      deliveryCompany: shipmentForm.shippingCompany,
      deliveryNo: shipmentForm.trackingNumber
    }

    const response = await orderApi.shipOrder(props.order.id, shipmentData)
    
    if (response.code === 200) {
      layer.msg('发货成功', { icon: 1 })
      emit('refresh')
      handleCancel()
    } else {
      layer.msg(response.message || '发货失败', { icon: 2 })
    }
  } catch (error) {
    console.error('发货失败:', error)
    layer.msg('发货失败', { icon: 2 })
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.shipment-dialog {
  padding: 20px;
}

.order-info {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.order-info h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.order-summary {
  display: grid;
  gap: 8px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.summary-item .value {
  color: #333;
  flex: 1;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  margin-left: 8px;
}

.tracking-validation {
  margin: 16px 0;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 4px;
}

.validation-result {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.validation-message {
  font-size: 12px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e6e6e6;
}

@media (max-width: 768px) {
  .shipment-dialog {
    padding: 16px;
  }
  
  .summary-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .summary-item .label {
    min-width: auto;
    margin-bottom: 4px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>